var mongo = require('mongodb');

 var Server = mongo.Server,
 Db = mongo.Db,
 BSON = mongo.BSONPure;

 var server = new Server('localhost', 27017, {auto_reconnect: true});
 db = new Db('RenterDB', server);


var Post = require('../app/models/post').Post;

exports.findAll = function(req, res) {
/*    Post.find({}, function (err, doc) {
        if (!err && doc) {
            res.json(200, doc);
        } else if (err) {
        res.json(500, { message: "Error loading post." + err});
        } else {
            res.json(404, { message: "Post not found."});
        }
    });*/

    /*    Post.find(function (err, items) {
     if(!err && items) {
     res.send(items);
     }else if (err) {
     res.send(500, { message: "Error loading post." + err});
     } else {
     res.send(404, { message: "Post not found."});
     }
     });*/

    console.log('Coucou');
    Post.find(function (err, posts) {
        res.send(posts);
    });
};


exports.findById = function (req, res) {
    var id = req.params.id; // The id of the user the user wants to look up.
    console.log('Retrieving post: ' + id);
    Post.findOne(id, function (err, doc) {
        if (!err && doc) {
            res.json(200, doc);
        } else if (err) {
            res.json(500, { message: "Error loading post." + err});
        } else {
            res.json(404, { message: "Post not found."});
        }
    });
};

exports.findByCity = function(req, res){
  /*var city = req.params.city;
    console.log('Retrieving post: ' + city);
    Post.findOne(city, function(){
        if (!err && doc) {
            res.json(200, doc);
        } else if (err) {
            res.json(500, { message: "Error loading post." + err});
        } else {
            res.json(404, { message: "Post not found."});
        }
    });*/
    console.log('Retrieving post: ' + req.body);
    Post.find(function (err, items) {
        res.send(items);
    });
};

exports.findSearchedPost = function(req, res){
    console.log('inside findSearchedPost');
    console.log('Retrieving post: ' + req.body);
    var city = req.body.city;
    var region = req.body.region;
    var country = req.body.country;


    Post.find({ city: city, region: region, country: country }, function(err, posts){
        res.send(posts);
    });
};
/*
 exports.addPost = function(req, res) {

 var firstname = req.body.firstname;  // Description of the user
 var lastname = req.body.lastname; // Scene name of the user
 var avatar = req.body.avatar; // Avatar of the user
 var birthdate = req.body.birthdate; // Birth date of the user
 var login = req.body.login; // Avatar of the user
 var password = req.body.password; // Avatar of the user
 var followedGroupId = req.body.followedGroupId; // Event identifier of the user
 var eventid = req.body.eventid; // Event identifier of the user
 var emailadress = req.body.emailaddress // User email address

 //User.findOne({ name: scenename }, function(err, doc) {  // This line is case sensitive.
 User.findOne({ emailadress: { $regex: new RegExp(emailadress, "i") } }, function(err, doc) {  // Using RegEx - search is case insensitive
 if(!err && !doc) {

 var newUser = new User();

 newUser.firstname = firstname;
 newUser.lastname = lastname;
 newUser.avatar = avatar;
 newUser.birthdate = birthdate;
 newUser.login = login;
 newUser.password = password;
 newUser.followedGroupId = followedGroupId;
 newUser.eventid = eventid;
 newUser.emailaddress = emailadress;

 newUser.save(function(err) {

 if(!err) {
 res.json(201, {message: "User created with first name: " + newUser.firstname });
 } else {
 res.json(500, {message: "Could not create user. Error: " + err});
 }

 });

 } else if(!err) {

 // User is trying to create a user with a name that already exists.
 res.json(403, {message: "User with that name already exists, please update instead of create or create a new user with a different name."});

 } else {
 res.json(500, { message: err});
 }
 });
 }*/


/*db.open(function (err, db) {
    if (!err) {
        console.log("Connected to 'RenterDB' database");
        db.collection('posts', {strict: true}, function (err, collection) {
            if (err) {
                console.log("The 'posts' collection doesn't exist. Creating it with sample data...");
                populateDB();
            }
        });
    }
});*/


/*
 exports.findById = function(req, res) {

 /*exports.findById = function (req, res) {
 var id = req.params.id;
 console.log('Retrieving post: ' + id);
 db.collection('posts', function (err, collection) {
 collection.findOne({'_id': new BSON.ObjectID(id)}, function (err, item) {
 res.send(item);
 });
 });
 };*/



/*

 exports.findAll = function (req, res) {
 db.collection('posts', function (err, collection) {
 collection.find().toArray(function (err, items) {
 res.send(items);
 });
 });
 };

 exports.addPost = function (req, res) {
 var post = req.body;
 console.log('Adding post: ' + JSON.stringify(post));
 db.collection('posts', function (err, collection) {
 collection.insert(post, {safe: true}, function (err, result) {
 if (err) {
 res.send({'error': 'An error has occurred'});
 } else {
 console.log('Success: ' + JSON.stringify(result[0]));
 res.send(result[0]);
 }
 });
 });
 };

 exports.updatePost = function (req, res) {
 var id = req.params.id;
 var post = req.body;
 console.log('Updating post: ' + id);
 console.log(JSON.stringify(post));
 db.collection('posts', function (err, collection) {
 collection.update({'_id': new BSON.ObjectID(id)}, post, {safe: true}, function (err, result) {
 if (err) {
 console.log('Error updating post: ' + err);
 res.send({'error': 'An error has occurred'});
 } else {
 console.log('' + result + ' document(s) updated');
 res.send(post);
 }
 });
 });
 };

 exports.deletePost = function (req, res) {
 var id = req.params.id;
 console.log('Deleting post: ' + id);
 db.collection('posts', function (err, collection) {
 collection.remove({'_id': new BSON.ObjectID(id)}, {safe: true}, function (err, result) {
 if (err) {
 res.send({'error': 'An error has occurred - ' + err});
 } else {
 console.log('' + result + ' document(s) deleted');
 res.send(req.body);
 }
 });
 });
 };
 */


/*--------------------------------------------------------------------------------------------------------------------*/

// Populate database with sample data -- Only used once: the first time the application is started.
// You'd typically not find this code in a real-life app, since the database would already exist.
var populateDB = function () {

    var posts = [
        {
            creationDate: "2014/10/05 15:42:10",
            title: "Loue Deus Ex Machina 600cc",
            description: "This board is made for the waves of NY NJ. It is a 6'6'' Aloha Bean, in great shape. Very high quality board worth around $700. Plenty of volume for the mushy waves out here. Carbon fiber Futureflex rails facilitate thrashing. I love this board deeply- no dings, dents, or anything. Comes ready to go with leash, trackpad, boardbag, fins, and a wetsuit ( booties/gloves, if needed) of your choosing- Adult M.",
            startDate: "2014/10/10",
            endDate: "2014/11/10",
            bikeId: "1",
            street: "273 Avenue Charlevoix de Villiers",
            postCode: "40150",
            city: "Soorts-Hossegor",
            region: "Aquitaine",
            country: "France",
            user_id: "54457ab4564bff3c27d6f609"
        },
        {
            creationDate: "2014/09/15 12:42:50",
            title: "Loue Deus Ex Machina 1000cc",
            description: "This bike is made for the waves of NY NJ. It is a 6'6'' Aloha Bean, in great shape. Very high quality board worth around $700. Plenty of volume for the mushy waves out here. Carbon fiber Futureflex rails facilitate thrashing. I love this board deeply- no dings, dents, or anything. Comes ready to go with leash, trackpad, boardbag, fins, and a wetsuit ( booties/gloves, if needed) of your choosing- Adult M.",
            startDate: "2014/09/20",
            endDate: "2014/10/19",
            bikeId: "1",
            street: "273 Avenue Charlevoix de Villiers",
            postCode: "40150",
            city: "Soorts-Hossegor",
            region: "Aquitaine",
            country: "France",
            user_id: "54457ab4564bff3c27d6f609"
        },
        {
            creationDate: "2014/09/15 12:42:50",
            title: "Loue Harley forty eight 2015",
            description: "This bike is made for the waves of NY NJ. It is a 6'6'' Aloha Bean, in great shape. Very high quality board worth around $700. Plenty of volume for the mushy waves out here. Carbon fiber Futureflex rails facilitate thrashing. I love this board deeply- no dings, dents, or anything. Comes ready to go with leash, trackpad, boardbag, fins, and a wetsuit ( booties/gloves, if needed) of your choosing- Adult M.",
            startDate: "2014/09/20",
            endDate: "2014/10/19",
            bikeId: "1",
            street: "273 La centrale",
            postCode: "33680",
            city: "Lacanau",
            region: "Aquitaine",
            country: "France",
            user_id: "54457ab4564bff3c27d6f609"
        },
        {
            creationDate: "2014/09/15 12:42:50",
            title: "Loue Harley forty eight 2015",
            description: "This bike is made for the waves of NY NJ. It is a 6'6'' Aloha Bean, in great shape. Very high quality board worth around $700. Plenty of volume for the mushy waves out here. Carbon fiber Futureflex rails facilitate thrashing. I love this board deeply- no dings, dents, or anything. Comes ready to go with leash, trackpad, boardbag, fins, and a wetsuit ( booties/gloves, if needed) of your choosing- Adult M.",
            startDate: "2014/09/20",
            endDate: "2014/10/19",
            bikeId: "1",
            street: "273 La centrale",
            postCode: "33680",
            city: "Saint-Louis",
            region: "Missouri",
            country: "Etats-Unis",
            user_id: "54457ab4564bff3c27d6f609"
        },
        {
            creationDate: "2014/09/15 12:42:50",
            title: "Loue Harley forty eight 2015",
            description: "This bike is made for the waves of NY NJ. It is a 6'6'' Aloha Bean, in great shape. Very high quality board worth around $700. Plenty of volume for the mushy waves out here. Carbon fiber Futureflex rails facilitate thrashing. I love this board deeply- no dings, dents, or anything. Comes ready to go with leash, trackpad, boardbag, fins, and a wetsuit ( booties/gloves, if needed) of your choosing- Adult M.",
            startDate: "2014/09/20",
            endDate: "2014/10/19",
            bikeId: "1",
            street: "273 La centrale",
            postCode: "33680",
            city: "Saint-Louis",
            region: "Oklahoma",
            country: "Etats-Unis",
            user_id: "54457ab4564bff3c27d6f609"
        }
    ];

    db.collection('posts', function (err, collection) {
        collection.insert(posts, {safe: true}, function (err, result) {
            console.log('Database created');
        });
    });

};
